package com.party.mobile.biz.order;

import com.alibaba.fastjson.JSONObject;
import com.party.common.utils.FileUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.CrowdfundRank;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.goods.GoodsCoupons;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAct;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.message.IdentityType;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.core.model.order.PaymentWay;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.crowdfund.ICrowdfundRankService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.goods.IGoodsCouponsService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.order.IOrderFormService;
import com.party.mobile.biz.crowdfund.PaintProjectPosterBiz;
import com.party.mobile.biz.crowdfund.ProjectBizService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.notify.notifyPush.officialPartner.ICopartnerNotifySendService;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 订单消息推送
 * Created by wei.li
 *
 * @date 2017/3/31 0031
 * @time 19:22
 */
@Service
public class MessageOrderBizService {

    @Autowired
    private INotifySendService notifySendService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IGoodsCouponsService goodsCouponsService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private ICrowdfundRankService crowdfundRankService;

    @Autowired
    private IOfficialPartnerNotifySendService officialPartnerNotifySendService;

    @Autowired
    private ICopartnerNotifySendService copartnerNotifySendService;

    @Autowired
    private ITargetCopartnerService targetCopartnerService;

    @Autowired
    private DistributorBizService distributorBizService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private PaintProjectPosterBiz paintProjectPosterBiz;

    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    private IDistributorDetailService distributorDetailService;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 订单短信推送
     *
     * @param orderId 订单号
     */
    public void send(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        GoodsCoupons t = new GoodsCoupons();
        t.setMemberId(orderForm.getMemberId());
        t.setGoodsId(orderForm.getGoodsId());
        t.setStatus(YesNoStatus.YES.getCode());
        List<GoodsCoupons> goodsCoupons = goodsCouponsService.list(t);
        for (GoodsCoupons coupons : goodsCoupons) {
            Member member = memberService.get(orderForm.getMemberId());
            MemberGroup orgMember = memberGroupService.get(orderForm.getInitiatorId());

            // 发送推送短信
            if (PaymentWay.CROWD_FUND_PAY.getCode().equals(orderForm.getPaymentWay())) {
                try {
                    notifySendService.sendCorowdfund(orderForm, coupons.getVerifyCode(), member, orgMember);
                } catch (Exception e) {
                    logger.error("众筹成功通知失败---通知众筹者", e);
                }
                TargetProject targetProject = targetProjectService.findByOrderId(orderForm.getId());
                try {
                    officialPartnerNotifySendService.sendCrowdfundSuccess(orderForm, member, orgMember, targetProject.getProjectId());
                } catch (Exception e) {
                    logger.error("众筹成功通知失败---通知合作商", e);
                }

                try {
                    // 代言人 合伙人 众筹成功消息推送
                    MemberAct memberAct = memberActService.findByOrderId(orderId);
                    String distributorId = distributorBizService.getDistributorId(memberAct.getId());
                    Integer distributionType = distributorBizService.getDistributorType(memberAct.getId());
                    if (StringUtils.isNotEmpty(distributorId) && distributionType != null) {
                        // 联合发起人推送
                        Member partnerReceiver = memberService.get(distributorId);
                        if (partnerReceiver != null) {
                            if (DistributorRelationType.CROWDFUND_REPRESENT.getCode().equals(distributionType)) {
                                copartnerNotifySendService.sendCrowdfundSuccess(orderForm, member, partnerReceiver.getId(),
                                        partnerReceiver.getMobile(), IdentityType.PARTNER.getCode(), targetProject.getProjectId());
                            } else if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(distributionType)) {
                                copartnerNotifySendService.sendCrowdfundSuccess(orderForm, member, partnerReceiver.getId(),
                                        partnerReceiver.getMobile(), IdentityType.CHANNEL_DIS.getCode(), targetProject.getProjectId());
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("众筹成功通知失败---通知联合发起人", e);
                }

                try {
                    // 合作渠道推送
                    Activity activity = activityService.get(orderForm.getGoodsId());
                    if (StringUtils.isNotEmpty(activity.getCosponsorId())) {
                        MemberGroup cosponsor = memberGroupService.get(activity.getCosponsorId());
                        if (cosponsor != null) {
                            copartnerNotifySendService.sendCrowdfundSuccess(orderForm, member, cosponsor.getId(),
                                    cosponsor.getMobile(), IdentityType.COSPONSOR.getCode(), targetProject.getProjectId());
                        }
                    }
                } catch (Exception e) {
                    logger.error("众筹成功通知失败---通知合作渠道", e);
                }
            } else {
                if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
                    try {
                        Activity activity = activityService.get(orderForm.getGoodsId());
                        notifySendService.sendActivityApply(orderForm, coupons.getVerifyCode(), activity, orgMember);
                    } catch (Exception e) {
                        logger.error("活动报名成功---通知报名者", e);
                    }
                    try {
                        officialPartnerNotifySendService.sendActivityApply(member.getRealname(), orderForm.getTitle(),
                                orderForm.getGoodsId(), orgMember.getMobile(), orgMember.getId());
                    } catch (Exception e) {
                        logger.error("活动报名成功---通知合作商", e);
                    }

                } else if (orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode()) || orderForm.getType().equals(OrderType.ORDER_CUSTOMIZED.getCode())) {
                    notifySendService.senGoodsBuy(orderForm, coupons.getVerifyCode());
                } else if (OrderType.ORDER_COURSE.getCode().equals(orderForm.getType())) {
                    Activity activity = activityService.get(orderForm.getGoodsId());
                    notifySendService.sendCourseApply(orderForm, coupons.getVerifyCode(), activity);
                }
            }
        }

    }

    /**
     * 活动审核拒绝推送
     *
     * @param orderId 订单号
     */
    public void activityRefundSend(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        if (orderForm.getPayment() > Float.valueOf("0.0")) {
            notifySendService.sendPayCheack(orderForm);
        } else {
            notifySendService.sendFreeCheack(orderForm);
        }
    }


    /**
     * 支持阶段短信推送
     *
     * @param orderForm 订单信息
     * @param project   项目编号
     */
    public void supportSend(OrderForm orderForm, Project project) {
        //项目开关
        TargetProject targetProject = targetProjectService.findByProjectId(project.getId());
        Activity activity = activityService.get(targetProject.getTargetId());

        if (YesNoStatus.NO.getCode().equals(activity.getCrowdfundHintSwitch())) {
            return;
        }
        //发送前十个人
        if (project.getFavorerNum() > 10) {
            return;
        }
        Member member = memberService.get(project.getAuthorId());
        notifySendService.sendSupportStage(orderForm, project, member);
    }


    /**
     * 发送众筹
     *
     * @param project         众筹信息
     * @param beforePercent   众筹之前的百分比
     * @param afterPercent    众筹之后的百分比
     * @param activity        众筹项目
     * @param crowdfundMember 众筹者
     * @param orgMember       发布者
     */
    public void projectGradationSend(Project project, final int beforePercent, final int afterPercent, Activity activity,
                                     Member crowdfundMember, MemberGroup orgMember) {
        if (YesNoStatus.NO.getCode().equals(activity.getCrowdfundHintSwitch())) {
            return;
        }
        if (afterPercent >= 10) {
            return;
        }
        //如果十位有变更 发送
        if (afterPercent > beforePercent) {
            CrowdfundRank crowdRank = crowdfundRankService.getCrowdRank(new CrowdfundRank("", activity.getId(),
                    project.getId()), afterPercent);
            notifySendService.sendProjectStage(project, crowdfundMember, afterPercent * 10,
                    crowdRank.getRankNo(), orgMember, activity);
        }
    }


    /**
     * @param orderForm       订单id
     * @param project         众筹
     * @param supportMember   支持者
     * @param crowdfundMember 众筹者
     * @param orgMember       发布者
     * @return
     * @Author yifeng
     * @Description 众筹支持消息推送
     * @Date 15:49 2019/4/11
     **/
    public void supportWechatSend(OrderForm orderForm, Project project, Member supportMember, Member crowdfundMember, MemberGroup orgMember) {
        logger.info("开始发送众筹支持通知>>>>OrderForm = {}, projectId = {}", JSONObject.toJSON(orderForm).toString(),
                project.getId());
        notifySendService.sendAcceptSupport(orderForm, supportMember, crowdfundMember, project.getId(), orgMember);
        logger.info("发送众筹支持结束");
    }


    /**
     * 免费活动推送
     *
     * @param type       类型
     * @param goodsId    活动/玩法ID
     * @param businessId 活动报名/玩法预定ID
     * @param memberId   当前用户ID
     */
    public void sendFree(Integer type, String goodsId, String businessId, String memberId) {
        GoodsCoupons t = new GoodsCoupons();
        t.setGoodsId(goodsId);
        t.setMemberId(memberId);
        t.setStatus(YesNoStatus.YES.getCode());
        List<GoodsCoupons> goodsCoupons = goodsCouponsService.list(t);

        MemberAct memberAct = memberActService.get(businessId);
        Activity activity = activityService.get(memberAct.getActId());
        Member member = memberService.get(memberAct.getMemberId());
        MemberGroup builder = memberGroupService.get(activity.getMember());
        for (GoodsCoupons coupons : goodsCoupons) {
            if (type.equals(OrderType.ORDER_ACTIVITY.getCode())) {
                notifySendService.sendActivityApplyFree(goodsId, businessId, coupons.getVerifyCode());

                officialPartnerNotifySendService.sendActivityApply(member.getRealname(),
                        activity.getTitle(), activity.getId(),
                        builder.getMobile(), builder.getId());
            } else if (OrderType.ORDER_COURSE.getCode().equals(type)) {
                notifySendService.sendCourseApplyFree(goodsId, businessId, coupons.getVerifyCode());
            }
        }
    }

    /**
     * 下单推送推送
     *
     * @param orderId 订单号
     */
    public void paySend(String orderId) {
        OrderForm orderForm = orderFormService.get(orderId);
        GoodsCoupons goodsCoupon = new GoodsCoupons();
        goodsCoupon.setOrderId(orderForm.getId());
        List<GoodsCoupons> goodsCoupons = goodsCouponsService.list(goodsCoupon);
        for (GoodsCoupons coupons : goodsCoupons) {
            if (orderForm.getType().equals(OrderType.ORDER_ACTIVITY.getCode())) {
                Member buyerMember = memberService.get(orderForm.getMemberId());
                MemberGroup orgMember = memberGroupService.get(orderForm.getInitiatorId());
                Activity activity = activityService.get(orderForm.getGoodsId());
                notifySendService.sendActivityApply(orderForm, coupons.getVerifyCode(), activity, orgMember);

                officialPartnerNotifySendService.sendActivityApply(buyerMember.getRealname(), orderForm.getTitle(),
                        orderForm.getGoodsId(), orgMember.getMobile(), orgMember.getId());

            } else if (orderForm.getType().equals(OrderType.ORDER_NOMAL.getCode()) || orderForm.getType().equals(OrderType.ORDER_CUSTOMIZED.getCode())) {
                notifySendService.senGoodsBuy(orderForm, coupons.getVerifyCode());
            }
        }
    }

    /**
     * 免费活动审核拒绝推送
     *
     * @param memberActId 活动报名id
     * @param activityId  活动id
     * @param memberId    用户id
     */
    public void freeActivityRejectSend(String memberActId, String activityId, String memberId) {
        MemberAct memberAct = memberActService.get(memberActId);
        OrderForm orderForm = new OrderForm();
        orderForm.setMemberId(memberId);
        orderForm.setGoodsId(activityId);
        orderForm.setId(memberActId);
        orderForm.setStatus(ActStatus.ACT_STATUS_AUDIT_REJECT.getCode());
        orderForm.setPhone(memberAct.getMobile());
        notifySendService.sendFreeCheack(orderForm);
    }

    /**
     * 众筹者成功海报发送
     *
     * @param projectId
     * @param authorId       接受者
     * @param targetMemberId 目标商户
     */
    public void raiseSuccessfulPostersSend(String projectId, String authorId, String targetMemberId,
                                           Member crowdfundMember, MemberGroup orgMember, Activity activity) {
        logger.info("开始众筹成功海报推送" + "projectId=" + projectId + "_____authorId=" + authorId + "_____targetMemberId=" + targetMemberId);
        File file = null;
        try {
            //获取海报
            long start = System.currentTimeMillis();
            byte[] bytes = projectBizService.paintProjectPoster(projectId, crowdfundMember, orgMember, activity);
            long end = System.currentTimeMillis();
            logger.info("paintProjectPoster   " + (end - start));
            file = this.posterSend(bytes, authorId, targetMemberId);
        } catch (Exception e) {
            logger.error("众筹成功海报推送失败", e);
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        logger.info("众筹成功海报推送结束");
    }

    /**
     * 众筹者成功海报发送
     *
     * @param projectId
     * @param authorId       接受者
     * @param targetMemberId 目标商户
     */
    public void raiseSuccessfulPostersSend(String projectId, String authorId, String targetMemberId) {
        logger.info("开始众筹成功海报推送", "projectId=" + projectId + "_____authorId=" + authorId + "_____targetMemberId=" + targetMemberId);
        File file = null;
        try {
            //获取海报
            byte[] bytes = projectBizService.paintProjectPoster(projectId);
            file = this.posterSend(bytes, authorId, targetMemberId);
        } catch (Exception e) {
            logger.error("众筹成功海报推送失败", e);
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        logger.info("众筹成功海报推送结束");
    }

    /**支持者支持海报发送
     * @param projectId
     * @param authorId            接受者
     * @param targetMemberId           目标商户
     */
    public void supportersPostersSend(String projectId, String authorId, String targetMemberId, String amount,
                                      Member crowdfundMember, MemberGroup orgMember, Activity activity, Member supportMember) {
        logger.info("开始支持海报推送" + "projectId=" + projectId + "_____authorId=" + authorId + "_____targetMemberId=" + targetMemberId);
        File file = null;
        try {
            //获取海报
            long start = System.currentTimeMillis();
            byte[] bytes = projectBizService.paintSupportersPoster(projectId, authorId, amount, crowdfundMember,
                    orgMember, activity, supportMember);
            long end = System.currentTimeMillis();
            logger.info("paintSupportersPoster   " + (end - start));
            file = this.posterSend(bytes, authorId, targetMemberId);
        } catch (Exception e) {
            logger.error("支持推送失败", e);
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        logger.info("支持海报推送结束");
    }

    /**支持者支持海报发送
     * @param projectId
     * @param authorId            接受者
     * @param targetMemberId           目标商户
     */
    public void supportersPostersSend(String projectId, String authorId, String targetMemberId, String amount) {
        logger.info("开始支持海报推送" + "projectId=" + projectId + "_____authorId=" + authorId + "_____targetMemberId=" + targetMemberId);
        File file = null;
        try {
            //获取海报
            byte[] bytes = projectBizService.paintSupportersPoster(projectId, authorId, amount);
            file = this.posterSend(bytes, authorId, targetMemberId);
        } catch (Exception e) {
            logger.error("支持推送失败", e);
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
        logger.info("支持海报推送结束");
    }

    public File posterSend(byte [] bytes, String authorId, String targetMemberId) throws Exception {
        //写人本地
        String imgFileUrl = paintProjectPosterBiz.getXmlPath() + "image" + File.separator + "raisePostersImg" + File.separator + authorId + ".png";
        System.out.println("海报URL = " + imgFileUrl);
        File pfile = new File(imgFileUrl);
        FileUtils.writeByteArrayToFile(pfile, bytes);
        //推送海报
        notifySendService.postersSend(authorId, targetMemberId, "image", pfile);
        //删除海报
        pfile.delete();
        return pfile;
    }
}
